import {
	apiBaseUrl
} from './config.js';
import * as common from './common.js' //引入common
import * as db from './db.js' //引入common
// 需要登陆的，都写到这里，否则就是不需要登陆的接口
const methodsToken = ['api/wx/decryptphone'];


const post = (method, data, callback, complete) => {
	uni.removeStorage({
		key: 'jump'
	})
	// 获取用户token
	let headers = {
		'Accept': 'application/json',
		'Content-Type': 'application/x-www-form-urlencoded'
	}
	let userToken = db.get("userToken");
	// if (!userToken) {
	// 	common.jumpToLogin();
	// 	return false;
	// } else {
	// 	headers.Authorization=userToken
	// }
	if(userToken){
		
		headers.Authorization = userToken
	}
	let postData = JSON.parse(JSON.stringify(data))
	delete postData.methodType
	uni.request({
		url: apiBaseUrl + method,
		data: postData,
		header: headers,
		method: data.methodType || 'post',
		success: (response) => {
			const result = response.data
			if (!result.status) {
				// 登录信息过期或者未登录
				if (result.code === 201) {
					db.del("userToken");
					let jump = uni.getStorageSync('jump')

					if (!jump) {
						uni.showToast({
							title: result.message,
							icon: 'none',
							duration: 1000,
							complete: function() {
								setTimeout(function() {
									uni.hideToast();
									uni.navigateTo({
										url: '/pages/login/login'
									})
								}, 1000)
							}
						});
						uni.setStorageSync('jump', true)
					}
				}
			}
			callback(result);
		},

		complete: (response) => {
			setTimeout(function() {
				uni.hideLoading();
			}, 1000)
			complete ? complete() : "";
		},
		fail: (error) => {
			uni.showLoading({
				title: '网络开小差了'
			});
			// setTimeout(function() {
			uni.hideLoading();
			// }, 1000)
			if (error && error.response) {
				showError(error.response);
			} else {

			}

		},
	});

}
const get = (url, callback) => {
	uni.showLoading({
		title: '加载中'
	});
	uni.request({
		url: url,
		header: {
			'Accept': 'application/json',
			'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
		},
		method: 'GET',
		success: (response) => {
			uni.hideLoading();
			callback(response.data);
		},
		fail: (error) => {
			uni.hideLoading();
			if (error && error.response) {
				showError(error.response);
			}
		},
		complete: () => {
			setTimeout(function() {
				uni.hideLoading();
			}, 250);
		}
	});
}

const showError = error => {
	let errorMsg = ''
	switch (error.status) {
		case 400:
			errorMsg = '请求参数错误'
			break
		case 401:
			errorMsg = '未授权，请登录'
			break
		case 403:
			errorMsg = '跨域拒绝访问'
			break
		case 404:
			errorMsg = `请求地址出错: ${error.config.url}`
			break
		case 408:
			errorMsg = '请求超时'
			break
		case 500:
			errorMsg = '服务器内部错误'
			break
		case 501:
			errorMsg = '服务未实现'
			break
		case 502:
			errorMsg = '网关错误'
			break
		case 503:
			errorMsg = '服务不可用'
			break
		case 504:
			errorMsg = '网关超时'
			break
		case 505:
			errorMsg = 'HTTP版本不受支持'
			break
		default:
			errorMsg = error.msg
			break
	}

	uni.showToast({
		title: errorMsg,
		icon: 'none',
		duration: 1000,
		complete: function() {
			setTimeout(function() {
				uni.hideToast();
			}, 1000);
		}
	});
}

// 文件上传
export const uploadFiles = (callback) => {
	uni.chooseImage({
		success: (chooseImageRes) => {
			uni.showLoading({
				title: '上传中...'
			});
			const tempFilePaths = chooseImageRes.tempFilePaths;
			const uploadTask = uni.uploadFile({
				url: apiBaseUrl + 'api/index/worker.html', //仅为示例，非真实的接口地址
				filePath: tempFilePaths[0],
				fileType: 'image',
				name: 'file',
				headers: {
					'Accept': 'application/json',
					'Content-Type': 'multipart/form-data',
				},
				formData: {
					'method': 'images.upload',
					'upfile': tempFilePaths[0]
				},
				success: (uploadFileRes) => {
					callback(JSON.parse(uploadFileRes.data));
				},
				fail: (error) => {
					if (error && error.response) {
						showError(error.response);
					}
				},
				complete: () => {
					setTimeout(function() {
						uni.hideLoading();
					}, 250);
				}
			});
		}
	});
}


// 首页轮播图
export const adList = (data, callback) => post('api/ad/list', data, callback);
// 产品分类
export const categoryList = (data, callback) => post('api/category/list', data, callback);
export const productDetail = (data, callback) => post('api/product/detail', data, callback);


// 首页商品数据
// 类型（0：首页；1：抽盒；2：会员购），不填默认为首页
export const productList= (data, callback) => post('api/product/search', data, callback);

// 位置（1：首页；2：秒杀活动页；3：砍价活动页；4：限时折扣页；5：满减送页），
export const dictDataList= (data, callback) => post('api/dict-data/list', data, callback);


// 用户信息
export const userInfo = (data, callback) => post('api/member/info', data, callback);
// 修改用户信息
export const userUpdate = (data, callback) => post('api/member/update', data, callback);
// 微信登录
export const wxLogin = (data, callback) => post('api/wx/login', data, callback);
// 微信获取手机号码
export const wxPhone = (data, callback) => post('api/wx/decryptphone', data, callback);

// 抽盒详情
export const boxDetail = (data, callback) => post('api/product/box/detail', data, callback);
// 文章分类
export const articleCategory = (data, callback) => post('api/article/category/list', data, callback);

// 文章列表
export const articleList = (data, callback) => post('api/article/list', data, callback);

// 文章详情
export const articleDetail = (data, callback) => post('api/article/detail', data, callback);


// 地址管理
export const getAreaList = (data, callback) => post('api/area/tree', data, callback);
export const addressCreate = (data, callback) => post('api/address/create', data, callback);
export const addressUpdate = (data, callback) => post('api/address/update', data, callback);
export const addressDelete = (data, callback) => post('api/address/delete', data, callback);
export const addressGet = (data, callback) => post('api/address/get', data, callback);
export const addressGetDefault = (data, callback) => post('api/address/get-default', data, callback);
export const addressList= (data, callback) => post('api/address/list', data, callback);

// 购物车管理
export const cartList = (data, callback) => post('/api/cart/list', data, callback);
export const cartAdd = (data, callback) => post('/api/cart/add', data, callback);
export const cartUpdateCount = (data, callback) => post('/api/cart/update-count', data, callback);
export const cartUpdateSelected = (data, callback) => post('/api/cart/update-selected', data, callback);
export const cartDelete = (data, callback) => post('/api/cart/delete', data, callback);
export const cartGetCount = (data, callback) => post('/api/cart/get-count', data, callback);